package com.ego.service;

import com.ego.exception.enums.ExceptionEnum;
import com.ego.exception.exception.EgoException;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


@Service
@Slf4j
public class UploadService {

    @Resource
    private FastFileStorageClient storageClient;

    /*上传*/
    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("png", "jpg","jpeg");

    public String upload(MultipartFile file) {
        String result = null;
        //验证格式
        try {
            String originalFilename = file.getOriginalFilename();
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            if (!suffixes.contains(ext)){
                EgoException.error(log,ExceptionEnum.INVALID_FILE_FORMAT);
            }
            String fileName = UUID.randomUUID().toString()+"."+ext;
            //保存到硬盘
            File dir = new File("D://images");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            /*file.transferTo(new File("D://images/upload/"+fileName));*/
            StorePath storePath = this.storageClient.uploadFile(
                    file.getInputStream(), file.getSize(), fileName, null);
            //result = "http://image.ego.com/upload/"+fileName;
            result = "http://image.ego.com/"+storePath.getFullPath();
            //拼接地址

        }catch (Exception e){
                EgoException.error(log,ExceptionEnum.UPLOAD_IMAGE_EXCEPTION,e);
        }
        return result;
    }
}
